package com.mall.order.mq.producer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
@Slf4j
public class DelayOrderProducer {

    private DefaultMQProducer producer;
    @PostConstruct
    public void init(){
        producer = new DefaultMQProducer("delay-order-producer");
        producer.setNamesrvAddr("127.0.0.1:9876");
        try {
            producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    public void sendMail(String orderId){
        Message message = new Message("delayOrder","orderMsg1",orderId.getBytes());
        message.setDelayTimeLevel(4);
        SendResult sendResult = null;
        try {
            //设置延迟消费时间,半小时之后检查订单是否支付,如果未支付就删除订单
            sendResult = producer.send(message);
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (sendResult != null && SendStatus.SEND_OK.equals(sendResult.getSendStatus())) {
            log.info("创建订单消息发送成功： " + sendResult.getMsgId());
            return;
        }
        log.info("创建订单消息发送失败");
    }
}
